from queue import Queue
from detect.detector import Detector
from tools.log import logger
from workers import h264_camera_worker,notify_worker
from PIL import Image
import time
import numpy as np
frame_ququqe=Queue(maxsize=20)

def notify(ts,meta):
    with h264_camera_worker.h264_lock:
            # 通知h264导出视频
            h264_camera_worker.h264_save_buffer.append((ts,meta))


def get_latest_frame():
    """
    获取队列中最新的一帧：
    - 队列空时阻塞等待
    - 取出第一帧后清空剩余旧帧
    """
    # 阻塞等待获取第一帧
    frame,ts = frame_ququqe.get()  # 阻塞，直到队列有元素

    # 清空剩余旧帧
    while True:
        try:
            frame_ququqe.get_nowait()
        except Exception as e:
            break
    return frame,ts

def work(global_conf,camera_conf):
    start = time.time()
    cnt=0
    detector = Detector(global_conf,camera_conf)
    while True:
        frame,ts = get_latest_frame()
        if not detector.loaded:
            detector.init_info(frame)
            detector.loaded=True
        else:
            cnt+=1
            boxes,classes,scores = detector.rknn.predict(frame)
            caplist = []
            detections = None
            if scores is not None:
                boxes,classes,scores = detector.reflex(boxes,classes,scores)
                if scores.size>0:
                    detections  = np.column_stack((boxes,scores,classes))
            tracks = detector.bytetracker.update(detections)
            
            for track in tracks:
                if track.is_captured or track.posivec is None:
                    continue
                track.is_captured=True 
                meta = detector.make_and_load_meta(ts=ts)
                meta["vehicle"] = int(track.cls)
                meta["direction"] = 0 if np.dot(track.posivec,detector.positive_vec) >0 else 1            
                notify_worker.notify_buffer.put((frame,meta))
        if cnt%120==0:  # 测试导出使用   
            # meta = detector.make_and_load_meta(ts=ts)
            # meta["vehicle"] = 0
            # meta["direction"] = 0          
            # notify_worker.notify_buffer.put((frame,meta))
            logger.info(f" detector:: {cnt/(time.time()-start)}fps")
